package me.shurufa.widget.popupwindow;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsoluteLayout;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import net.qiujuer.genius.blur.StackBlur;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.event.EventObject;
import me.shurufa.model.Digest;
import me.shurufa.model.DigestResponse;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.NetworkConstants;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.FastBlur;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.Utils;

/**
 * 在此写用途
 *
 * @FileName: me.shurufa.widget.popupwindow.EditDigestPopWindow.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-02-13 00:21
 */
public class EditDigestPopWindow extends PopupWindow implements View.OnClickListener {

    Activity mContext;
    private int mWidth;
    private int mHeight;
    private int statusBarHeight;
    private Bitmap mBitmap = null;
    private Bitmap overlay = null;
    private ScaleAnimation mShowAnim;


    View outView;

    private InputMethodManager imm;
    private Digest digest;
    private TextView saveButton;
    private EditText noteEdit;
    private EditText digestEdit;
    private TextView stateButton;

    public EditDigestPopWindow(Activity context) {
        mContext = context;
    }


    /**
     * 设置宽高为除去上方状态栏的全屏
     * 实例化后需要手动调用
     */
    public void init(Digest digest) {
        this.digest = digest;
        Rect frame = new Rect();
        mContext.getWindow().getDecorView()
                .getWindowVisibleDisplayFrame(frame);
        statusBarHeight = frame.top;
        DisplayMetrics metrics = new DisplayMetrics();
        mContext.getWindowManager().getDefaultDisplay()
                .getMetrics(metrics);
        mWidth = metrics.widthPixels;
        mHeight = metrics.heightPixels;

        setWidth(mWidth);
        setHeight(mHeight);
        mShowAnim = new ScaleAnimation(0.5f, 1f, 0.5f, 1f, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        mShowAnim.setFillAfter(true);
        mShowAnim.setDuration(500);
    }


    /**
     * Java method to blur by FastBlur
     *
     * @return
     */
    private Bitmap blur() {
        if (null != overlay) {
            return overlay;
        }
        long startMs = System.currentTimeMillis();

        View view = mContext.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        mBitmap = view.getDrawingCache();
        // TODO 去掉通知栏
        int width = mBitmap.getWidth();
        int height = mBitmap.getHeight();
        mBitmap = Bitmap.createBitmap(mBitmap, 0, statusBarHeight, width, height - statusBarHeight);
        height -= statusBarHeight;
        float scaleFactor = 8;// 缩放比例
        float radius = 3;// 模糊程度


        overlay = Bitmap.createBitmap((int) (width / scaleFactor), (int) (height / scaleFactor),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(overlay);
        canvas.scale(1 / scaleFactor, 1 / scaleFactor);
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG);
        canvas.drawBitmap(mBitmap, 0, 0, paint);

        overlay = FastBlur.doBlur(overlay, (int) radius, true);
        Log.i("EditDigestWindow", "blur time is:" + (System.currentTimeMillis() - startMs));
        return overlay;
    }


    private Bitmap blur(int i) {


        long startMs = System.currentTimeMillis();

        // Is scale
        View view = mContext.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        mBitmap = view.getDrawingCache();
        // TODO 去掉通知栏
        int width = mBitmap.getWidth();
        int height = mBitmap.getHeight();
        mBitmap = Bitmap.createBitmap(mBitmap, 0, statusBarHeight, width, height - statusBarHeight);
        height -= statusBarHeight;
        float scaleFactor = 8;// 缩放比例
        float radius = 3;// 模糊程度

        overlay = Bitmap.createBitmap((int) (width / scaleFactor), (int) (height / scaleFactor),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(overlay);
        canvas.scale(1 / scaleFactor, 1 / scaleFactor);
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG);
        canvas.drawBitmap(mBitmap, 0, 0, paint);


        // is blur
        // Java
        if (i == 1)
            overlay = StackBlur.blur(overlay, (int) radius, false);
            // Bitmap JNI Native
        else if (i == 2)
            overlay = StackBlur.blurNatively(overlay, (int) radius, false);
            // Pixels JNI Native
        else if (i == 3)
            overlay = StackBlur.blurNativelyPixels(overlay, (int) radius, false);

        Log.i("EditDigestWindow", "blur time is:" + (System.currentTimeMillis() - startMs));
        return overlay;
    }


    /**
     * display
     *
     * @param anchor
     * @param bottomMargin
     */
    public void showMoreWindow(View anchor, int bottomMargin) {
        final View rootView = LayoutInflater
                .from(mContext).inflate(R.layout.pop_edit_digest, null);
//    监听返回键
        rootView.setFocusableInTouchMode(true);
        saveButton = (TextView) rootView.findViewById(R.id.pop_save);
        noteEdit = (EditText) rootView.findViewById(R.id.edit_note);
        digestEdit = (EditText)rootView.findViewById(R.id.edit_digest);
        stateButton = (TextView)rootView.findViewById(R.id.pop_state);
        if (digest!=null){
            if (!TextUtils.isEmpty(digest.content))
                digestEdit.setText(digest.content);
            if (!TextUtils.isEmpty(digest.note))
                noteEdit.setText(digest.note);
        }
        stateButton.setText(checkState(digest.publish_state));
        stateButton.setOnClickListener(this);
        saveButton.setOnClickListener(this);
        setContentView(rootView);
        setAnimationStyle(android.R.style.Animation_Toast);
        android.widget.RelativeLayout.LayoutParams params =
                new android.widget.RelativeLayout.LayoutParams(AbsoluteLayout.LayoutParams.WRAP_CONTENT,
                        AbsoluteLayout.LayoutParams.WRAP_CONTENT);
        params.bottomMargin = bottomMargin;
        params.topMargin = 200;
        params.leftMargin = 18;

        // TODO 设置内部控件 Anim

        // 设置背景高斯模糊
        setBackgroundDrawable(new BitmapDrawable(mContext.getResources(), blur(2)));

        // 外部是否可以点击
        setOutsideTouchable(true);
        setFocusable(true);
        showAtLocation(anchor, Gravity.BOTTOM, 0, statusBarHeight);
        //imm.showSoftInputFromInputMethod(editText.getWindowToken(),0);
        digestEdit.setFocusable(true);
        digestEdit.setFocusableInTouchMode(true);
        digestEdit.requestFocus();
//        Timer timer = new Timer();
//        timer.schedule(new TimerTask() {
//            public void run() {
//                imm = (InputMethodManager) digestEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//                imm.showSoftInput(digestEdit, 0);
//            }
//
//        }, 500);
    }


    public String checkState(String str){
        if (str.equals("publish"))
            return mContext.getString(R.string.has_published);
        else
            return mContext.getString(R.string.not_publish);
    }

    @Override
    public void dismiss() {
        destroy();
        super.dismiss();
    }


    public void destroy() {
        if (null != overlay) {
            overlay.recycle();
            overlay = null;
            System.gc();
        }
        if (null != mBitmap) {
            mBitmap.recycle();
            mBitmap = null;
            System.gc();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pop_save:
                final String digestTrim = digestEdit.getText().toString().trim();
                final String noteTrim = noteEdit.getText().toString().trim();
                if (!TextUtils.isEmpty(digestTrim)) {
                    new RequestServerTask<DigestResponse>(DigestResponse.class, mContext, mContext.getString(R.string.commit_pls_wait)) {

                        @Override
                        protected String requestServer() {
                            Map<String, Object> params = new HashMap<>();
                            params.put("token",Global.currentUser.token);
                            params.put("excerptId",digest.id);
                            params.put("content",digestTrim);
                            params.put("note",noteTrim);
                            params.put("publishState",digest.publish_state);
//                            when i request not add screenshot,response is screenshot is required.Fuck and Why?
                            params.put("screenshot","why this must be required?");
                            return HttpUtil.post(NetworkConstants.MODIFY_DIGEST, params);
                        }

                        @Override
                        protected void onSuccess(DigestResponse result) {
                            if (result.success) {
                                //替换Digest列表中的数据 发消息给列表fragment
                                EventObject object = new EventObject();
                                object.setEventAction(Constants.ACTION_MODIFY_MY_DIGEST);
                                object.setDigest(result.data);
                                EventBus.getDefault().post(object);
                                EditDigestPopWindow.this.dismiss();
                            }
                        }
                    }.start();
                } else {
                    Utils.showToast(mContext.getString(R.string.content_is_empty));
                }
                break;
            case R.id.pop_state:
                if (digest.publish_state.equals("publish")){
                    digest.publish_state="save";
                    stateButton.setText(mContext.getString(R.string.not_publish));
                }else{
                    digest.publish_state="publish";
                    stateButton.setText(mContext.getString(R.string.has_published));
                }
                break;
        }
    }
}
